package tenant

import (
	"cgs-server/helper"
	"cgs-server/server"
	"cgs-server/server/base"
	"go.mongodb.org/mongo-driver/bson"
	"net/http"
)

func init() {
	server.Post("/api/Tenant/Info/Add", AddTenantInfo, "添加租户信息", server.ManageBackend)
	server.Post("/api/Tenant/Info/Update", UpdateTenantInfo, "更新租户信息", server.ManageBackend)
	server.Get("/api/Tenant/Info/List", ListTenantInfo, "获取租户信息列表", server.Login)
	server.Get("/api/Tenant/Info/GetByTenantId", GetInfoByTenantId, "获取租户信息", server.None)
	server.Post("/api/Tenant/Info/Delete", DeleteTenantInfo, "删除租户信息", server.ManageBackend)
}

// 添加租户
func AddTenantInfo(w http.ResponseWriter, r *http.Request) {
	// 租户名称
	tenantInfo := &TenantInfo{}
	err := helper.ReadRequestBody(tenantInfo, w, r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	dataUserModel := base.GenerateDataUserModel(tenantInfo, r)
	tenantService := NewTenantInfoService()
	err = tenantService.Save(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK().WithData(bson.M{"tenantInfo": tenantInfo}))
}

func UpdateTenantInfo(w http.ResponseWriter, r *http.Request) {
	tenantInfo := &TenantInfo{}
	err := helper.ReadRequestBody(tenantInfo, w, r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	tenantService := NewTenantInfoService()
	dataUserModel := base.GenerateDataUserModel(tenantInfo, r)
	err = tenantService.Update(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Update successfully!"))
}

func ListTenantInfo(w http.ResponseWriter, r *http.Request) {
	tenantService := NewTenantInfoService()
	dataUserModel := base.GenerateDataUserModel(&TenantInfo{}, r)
	data, err := tenantService.List(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK().WithData(data))
}

func GetInfoByTenantId(w http.ResponseWriter, r *http.Request) {
	tenantId := r.FormValue("tenantId")

	tenantService := NewTenantInfoService()
	currentUser, err := base.GetCurrentUser(r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	result, err := tenantService.GetByTenantId(tenantId, currentUser)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK().WithData(result))
}

func DeleteTenantInfo(w http.ResponseWriter, r *http.Request) {
	tenantId := r.FormValue("tenantId")

	tenantService := NewTenantInfoService()
	user, err := base.GetCurrentUser(r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	err = tenantService.RemoveLogicByTenantId(tenantId, user)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail("Delete failed."))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Delete successfully!"))
}

